<?php 
include("helper/DBOperation.php");
error_reporting(E_ALL);
ini_set('display_errors','On');
$dbObj = new DBOperation();

$message = ""; 
$alertType = array("green"=>1,"red"=>3,"yellow"=>2);
$msgId = array();
$query = "select id,component_name from tbl_components";
$componentsResult = mysql_query($query);
$alerts = array();
$secondStatus = null;
$test_color = array();
if(mysql_num_rows($componentsResult) > 0){
	while($component = mysql_fetch_assoc($componentsResult)){
		$limit = 2 ;
		$secondStatus = null;
		if($componentsResult['component_name'] == 'Displays'){
			$limit = 10;
		}
		
		$componentStatus = mysql_query("select * from tbl_component_state where component_id = ".$component['id']." order by id desc limit 0,".$limit);			
		
		if((mysql_num_rows($componentStatus)==$limit) || ($limit ==2 && mysql_num_rows($componentStatus)==1 ) || ($limit ==10 && mysql_num_rows($componentStatus)>=5 )){
			if($limit == 5){
				$temp ="";
				for($i=0;$i<5;$i++){
					$temp = mysql_fetch_assoc($componentStatus);
					$test_color[] = $temp['state'];
				}
				$test_state ="";
				if(in_array("red", $test_color)){
					$test_state  = "red";
				}elseif(in_array("yellow", $test_color)){
					$test_state  = "yellow";
				}elseif(in_array("green", $test_color)){
					$test_state  = "green";
				}
				$firstStatus  = $temp;
				$firstStatus['state'] = $test_state;
				
			}else{
				$firstStatus = mysql_fetch_assoc($componentStatus);
			}
			if($limit ==10 && mysql_num_rows($componentStatus)==10 ){
				$temp ="";
				for($i=0;$i<5;$i++){
					$temp = mysql_fetch_assoc($componentStatus);
					$test_color[] = $temp['state'];
				}
				$test_state ="";
				if(in_array("red", $test_color)){
					$test_state  = "red";
				}elseif(in_array("yellow", $test_color)){
					$test_state  = "yellow";
				}elseif(in_array("green", $test_color)){
					$test_state  = "green";
				}
				$secondStatus  = $temp;
				$secondStatus['state'] = $test_state;
			}elseif($limit ==2 && mysql_num_rows($componentStatus)==2){			
				$secondStatus = mysql_fetch_assoc($componentStatus);
			}

			if($secondStatus != null && $firstStatus['state'] == $secondStatus['state']){
				//ignore all alert for it
				mysql_query("update tbl_log_message set is_sent = 0 where component_id=".$component['id']);
			}else{
				
				// need to send all alert for it
				if($firstStatus['state'] == 'green'){
					//cname,dname,clid,cdid
					$currentPingTime 	= strtotime(date("Y-m-d h:i:s"));
					$lastPingTime		= strtotime($firstStatus['datetime']) ;
					$pingDifference		= $currentPingTime - $lastPingTime;
					//echo round($pingDifference/60);
					$diff = $pingDifference ;
					if($diff < 300 ){
					$query = "select  tbl_components.id as clid,tbl_components.component_name as cname, tbl_components.device_id as cdid, tbl_device.device_name as dname
						  from tbl_components, tbl_device 
						  where  tbl_components.device_id = tbl_device.id and			
						   tbl_components.id =".$component['id'];
						$log_query = mysql_query($query);
						$row_log = mysql_fetch_array($log_query);
						
						//$alerts[$row_log['cdid'].$row_log['clid']."-".$row_log['clstatus']]["msg"][] = $row_log['clmsg'];
						//$alerts[$row_log['cdid'].$row_log['clid']."-".$row_log['clstatus']]["ids"][] = $row_log['id'];
						$alerts[$row_log['cdid'].$row_log['clid']]["data"] = $row_log;
						$alerts[$row_log['cdid'].$row_log['clid']]["data"]['clstatus']=1;
					}
				}
							
				$query = "select tbl_log_message.id as id, tbl_log_message.component_id as clid,tbl_log_message.created_date as cldate, 
						  tbl_log_message.message as clmsg, tbl_log_message.status as clstatus, tbl_log_message.is_sent as is_sent,
						  tbl_components.component_name as cname, tbl_components.device_id as cdid, tbl_device.device_name as dname
						  from tbl_log_message,tbl_components, tbl_device 
						  where tbl_log_message.component_id = tbl_components.id and
						  tbl_components.device_id = tbl_device.id and			
						  tbl_log_message.is_sent  = 1 and tbl_log_message.component_id ='".$component['id']."' and tbl_log_message.status ='".$alertType[$firstStatus['state']]."'  order by tbl_log_message.created_date desc";
				
				$log_query = mysql_query($query);
				if(mysql_num_rows($log_query)>0){

					while($row_log = mysql_fetch_array($log_query)){
						
						$alerts[$row_log['cdid'].$row_log['clid']."-".$row_log['clstatus']]["msg"][] = $row_log['clmsg'];
						$alerts[$row_log['cdid'].$row_log['clid']."-".$row_log['clstatus']]["ids"][] = $row_log['id'];
						$alerts[$row_log['cdid'].$row_log['clid']."-".$row_log['clstatus']]["data"] = $row_log;
		
					}
				}
	

			}
		}else{
			continue;
		}
	
	}

}


echo "\n\nCron Start at ==".date('d-m-Y H:i')."==";
if(count($alerts)>0){
	$user_query = mysql_query("select * from tbl_users where email_alert = 1");
	$user_query_text = mysql_query("select * from tbl_users where text_alert = 1");
	$users = array();
	$text_users = array();
	while($row = mysql_fetch_array($user_query)){
				$users[] = $row;
	}
	while($row2 = mysql_fetch_array($user_query_text)){
				$text_users[] = $row2;
	}


		foreach($alerts as $row_log){ //while start
			$message="";
			$name = "";
			if($row_log["data"]['cname'] == "CPUH" || $row_log["data"]['cname'] == "CPUV"){
				$row_cpu_name = mysql_fetch_array(mysql_query("select cpu_name from tbl_component_cpu where component_id = '".$row_log["data"]['clid']."' order by id desc"));
				$unit_name = $row_log["data"]['dname']." ".$row_log["data"]['cname'];
				$name = $row_cpu_name['cpu_name'];
				if($row_log["data"]['cname'] == "CPUH"){
					$link = "alert_log_cpuh.php?cid=".$row_log["data"]['clid']."&did=".$row_log["data"]['cdid'];
				}
				if($row_log["data"]['cname'] == "CPUV"){
					$link = "alert_log_cpuv.php?cid=".$row_log["data"]['clid']."&did=".$row_log["data"]['cdid'];
				}			
			}
			if($row_log["data"]['cname'] == "Displays"){
				$row_cpu_name = mysql_fetch_array(mysql_query("select display_name from tbl_component_display where component_id = '".$row_log["data"]['clid']."' order by id desc"));
				$unit_name = $row_log["data"]['dname']." ".$row_log["data"]['cname'];
				$name = $row_cpu_name['display_name'];
				$link = "alert_log.php?cid=".$row_log["data"]['clid']."&did=".$row_log["data"]['cdid'];
			}
			if($row_log["data"]['cname'] == "HVAC-H" || $row_log["data"]['cname'] == "HVAC-V"){
				$row_cpu_name = mysql_fetch_array(mysql_query("select hvac_unit_name from tbl_component_hvac where component_id = '".$row_log["data"]['clid']."' order by id desc"));
				$unit_name = $row_log["data"]['dname']." ".$row_log["data"]['cname'];
				$name = $row_cpu_name['hvac_unit_name'];
				$link = "alert_log_hvac.php?cid=".$row_log["data"]['clid']."&did=".$row_log["data"]['cdid'];
			}

			if($row_log["data"]['clstatus']==1){
				
				$subject= "[Cemusa Alert] ".$unit_name." is back to normal";
				$message.= "<div>You can relax now, ".$unit_name." is back and working fine.</div>";
			}
			if($row_log["data"]['clstatus']==2){
				$subject= "[Cemusa Alert] ".$unit_name." needs your attention";
				$message.= "<div>Please look into ".$unit_name.", it has the following alert condition:</div>";
					foreach($row_log["msg"] as $msg){
						$message.="<div>".$name.": ".$msg."</div>";
					}
			}
			if($row_log["data"]['clstatus']==3){
				$subject= "[Cemusa Alert] ".$unit_name." is critical or offline";
				$message.= "<div>Please look into ".$unit_name." immediately, it has the following critical condition which may have caused it go offline:</div>";
					foreach($row_log["msg"] as $msg){
						$message.="<div>".$name.": ".$msg."</div>";
					}

			}
		
		$message.=	"<br><div>Please click the link below to see the alert.<br><a href='".BASEPATH.$link."'>".$unit_name."</a></div>";  
		foreach($users as $user){
			// message sending start
			$from  = "cemusa@showandtell.com";
			$subject = $subject;
			$headers = "MIME-Version: 1.0" . "\r\n";
			$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
			$headers .= "From:" . $from. "\r\n";
			$body = "<p>Dear ".$user['username']." ,</p>".$message."<p>Regards,<br>Cemusa</p>";
			$email = $user['email'];		
			//print_r($email);echo "<br>";
			//print_r($subject);echo "<br>";
			//print_r($body);echo "<br>";
			//print_r($headers);echo "<br>";
			if(!mail($email,$subject,$body,$headers)){
				if(isset($row_log["ids"]))
				echo "\n Mail Not Sent for ".$email." and log id ".implode(",",$row_log["ids"])."\n<BR>";
			} 
	
		}
		foreach($text_users as $user){
			// message sending start
			$from  = "cemusa@showandtell.com";
			$subject = $subject;
			$headers = "MIME-Version: 1.0" . "\r\n";
			$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
			$headers .= "From:" . $from. "\r\n";
			$body = "<p>Dear ".$user['username']." ,</p>".$message."<p>Regards,<br>Cemusa</p>";
			$email = $user['phone']."@".$user['carrier'];		
			//print_r($email);echo "<br>";
			//print_r($subject);echo "<br>";
			//print_r($body);echo "<br>";
			//print_r($headers);echo "<br>";
			if(!mail($email,$subject,$body,$headers)){
				if(isset($row_log["ids"]))
				echo "\n Mail Not Sent for ".$email." and log id ".implode(",",$row_log["ids"])."\n<BR>";
			} 
	
		}
		if(isset($row_log["data"]['clid']))
		if(!mysql_query("update tbl_log_message set is_sent = 0 where component_id =".$row_log["data"]['clid']."")){
			echo "\nlog message status not changed for  ".$row_log["data"]['id'];
		}

		// message sending end
		
		}	// while end	
}else{
	echo "No log to send";
}

echo "\n\nCron End at ==".date('d-m-Y H:i')."==";

?>
